from rest_framework import serializers

from users.models import HouseListing, HouseType, HouseTransaction, ResidentialCommunity, School, Cart, Contract, RentContract, SellContract, ContractChangeLog, ContractPaymentRecord


class HouseListingSerializers(serializers.ModelSerializer):
    class Meta:
        model = HouseListing
        fields = '__all__'
class HouserTypeSerializers(serializers.ModelSerializer):
    class Meta:
        model = HouseType
        fields = '__all__'

class HouseTransactionSerializer(serializers.ModelSerializer):
    class Meta:
        model = HouseTransaction
        fields = '__all__'

class ResidentialCommunitySerializer(serializers.ModelSerializer):
    class Meta:
        model = ResidentialCommunity
        fields = '__all__'

class SchoolSerializer(serializers.ModelSerializer):
    class Meta:
        model = School
        fields = '__all__'

class CartSerializer(serializers.ModelSerializer):
    house = HouseListingSerializers(read_only=True)
    class Meta:
        model = Cart
        fields = '__all__'

# 新增合同序列化器
class ContractSerializer(serializers.ModelSerializer):
    house_address = serializers.CharField(source='house.address', read_only=True)
    house_type = serializers.CharField(source='house.house_type', read_only=True)
    area = serializers.DecimalField(source='house.area', max_digits=10, decimal_places=2, read_only=True)
    remarks = serializers.CharField(allow_blank=True, required=False)
    
    class Meta:
        model = Contract
        fields = [
            'id', 'contract_number', 'contract_type', 
            'house_address', 'house_type', 'area',
            'total_amount', 'deposit', 'remarks',
            'effective_time', 'expire_time',
            'created_at', 'updated_at'
        ]

class RentContractSerializer(serializers.ModelSerializer):
    contract = ContractSerializer()
    
    class Meta:
        model = RentContract
        fields = '__all__'

class SellContractSerializer(serializers.ModelSerializer):
    contract = ContractSerializer()
    
    class Meta:
        model = SellContract
        fields = '__all__'

class ContractCreateSerializer(serializers.Serializer):
    contract_type = serializers.ChoiceField(choices=Contract.CONTRACT_TYPES)
    house_id = serializers.IntegerField()
    tenant_id = serializers.IntegerField()
    total_amount = serializers.DecimalField(max_digits=12, decimal_places=2)
    deposit = serializers.DecimalField(max_digits=12, decimal_places=2)
    effective_time = serializers.DateField()
    expire_time = serializers.DateField()
    remarks = serializers.CharField(required=False, allow_blank=True)
    
    # 租赁合同特有字段
    rent = serializers.DecimalField(max_digits=10, decimal_places=2, required=False)
    payment_cycle = serializers.ChoiceField(choices=RentContract.PAYMENT_CYCLES, required=False)
    payment_due_day = serializers.IntegerField(required=False)
    grace_period = serializers.IntegerField(required=False)
    early_termination_allowed = serializers.BooleanField(required=False)
    early_termination_fee = serializers.DecimalField(max_digits=10, decimal_places=2, required=False)
    
    # 买卖合同特有字段
    house_price = serializers.DecimalField(max_digits=12, decimal_places=2, required=False)
    payment_method = serializers.ChoiceField(choices=SellContract.PAYMENT_METHODS, required=False)
    down_payment = serializers.DecimalField(max_digits=12, decimal_places=2, required=False)
    mortgage_bank = serializers.CharField(required=False, allow_blank=True)
    mortgage_amount = serializers.DecimalField(max_digits=12, decimal_places=2, required=False)
    transfer_date = serializers.DateField(required=False)
    property_handover_date = serializers.DateField(required=False)

    def validate(self, data):
        contract_type = data.get('contract_type')
        
        # 验证租赁合同必填字段
        if contract_type == 'RENT':
            required_fields = ['rent', 'payment_cycle', 'payment_due_day']
            for field in required_fields:
                if not data.get(field):
                    raise serializers.ValidationError(f"{field} is required for rent contracts")
        
        # 验证买卖合同必填字段
        elif contract_type == 'SELL':
            required_fields = ['house_price', 'payment_method', 'down_payment', 
                             'transfer_date', 'property_handover_date']
            for field in required_fields:
                if not data.get(field):
                    raise serializers.ValidationError(f"{field} is required for sell contracts")
        
        return data
